package com.endgamefraction.androidinfection;

import java.util.ArrayList;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.opengl.GLUtils;


// singleton asset loader for texture
public class AssetManager
{
	private int[] vTextures;
	private ArrayList<Integer> vID = new ArrayList<Integer>(50);
	private static AssetManager mInstance;
	private int index = 0;
	private int last = 0;
	
	private AssetManager()
	{
		vTextures = new int[50];
	}
	
	public static AssetManager GetInstance()
	{
		if( mInstance == null)
			mInstance = new AssetManager();
		
		return mInstance;
	}
	
	public int loadGameTexture(int id, Context context, GL10 gl)
	{
		// see if we already loaded the texture
		int len = vID.size();
		for( int i = 0; i < len; ++i )
		{
			if( vID.get(i) == id )
				return vTextures[i];
		}
		
		gl.glGenTextures(1, vTextures, 0);
		int texID = vTextures[last];
	 
		// ...and bind it to our array
		gl.glBindTexture(GL10.GL_TEXTURE_2D, texID);
	 
		// Create Nearest Filtered Texture
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
				GL10.GL_LINEAR);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
				GL10.GL_LINEAR);
	 
		// Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
				GL10.GL_CLAMP_TO_EDGE);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
				GL10.GL_REPEAT);
	 
		// Use the Android GLUtils to specify a two-dimensional texture image
		// from our bitmap
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, BitmapFactory.decodeResource(context.getResources(), id), 0);
		
		++last;
		
		// update the lists
		vID.add(id);
		
		return texID;
	}
	
	public int getTexture(int texID)
	{
		return vTextures[texID]; // return copy of the texture object
	}
	
	public void shutdown()
	{
	}
	
}


class Texture
{
	private Bitmap tex;
	private int id;
	public int refCount;
	
	Texture()
	{
		tex = null;
		id = -1;
	}
	
	// copy ctor
	public Texture(Texture t)
	{
		this.id = t.id;
		this.tex = t.tex;
	}
	
	public void setBitmap(Bitmap b) { tex = b; }
	public void setID(int _id) { id = _id; }
	
	public Bitmap getBitmap() { return tex; }
	public int getID() { return id; } 
}